<template>
  <div class="content">
    <div class="public2">
      <div class="content-left">主体资质</div>
      <div class="content-right">
        <el-form
          ref="ruleFormRef"
          :model="submitForm.subjectQualification"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          size="default"
          status-icon
          require-asterisk-position="right"
        >
          <el-form-item label="证件类型" prop="certificatesType">
            <el-select
              v-model="submitForm.subjectQualification.certificatesType"
              clearable
              placeholder="请选择证件类型"
            >
              <el-scrollbar height="170px">
                <el-option
                  v-for="item in subjectQualificationList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-scrollbar>
            </el-select>
          </el-form-item>
          <el-form-item
            label="资质照片"
            prop="certificatesPhoto"
            class="public"
          >
            <my-photo
              :imgurl="
                submitForm.subjectQualification.certificatesPhoto
                  ? 'http://zxc.ruanjian211.top/' +
                    submitForm.subjectQualification.certificatesPhoto
                  : ''
              "
              @photo-path="certificatesPhoto"
            ></my-photo>
          </el-form-item>
          <el-form-item label="注册号" prop="registerNumber">
            <el-input
              v-model="submitForm.subjectQualification.registerNumber"
              placeholder="请与资质照片上的保持一致"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="单位名称" prop="companyName">
            <el-input
              v-model="submitForm.subjectQualification.companyName"
              placeholder="请输入单位名称"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="法定代表人" prop="legalPerson">
            <el-input
              v-model="submitForm.subjectQualification.legalPerson"
              placeholder="请输入法定代表人名称"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="经营场所" prop="businessAddress">
            <el-input
              v-model="submitForm.subjectQualification.businessAddress"
              placeholder="请输入经营场所名称"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="有效期" prop="expirationDate">
            <el-date-picker
              v-model="submitForm.subjectQualification.expirationDate"
              type="date"
              placeholder="请选择日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="public2">
      <div class="content-left">行业资质</div>
      <div class="content-right">
        <el-form
          ref="ruleFormRefTwo"
          :model="submitForm.industryQualification"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          size="default"
          status-icon
          require-asterisk-position="right"
        >
          <el-form-item label="证件类型" prop="certificatesType">
            <el-select
              v-model="submitForm.industryQualification.certificatesType"
              clearable
              placeholder="请选择证件类型"
            >
              <el-scrollbar>
                <el-option
                  v-for="item in IndustryQualificationList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-scrollbar>
            </el-select>
          </el-form-item>
          <el-form-item
            label="资质照片"
            prop="certificatesPhoto"
            class="public"
          >
            <my-photo
              :imgurl="
                submitForm.industryQualification.certificatesPhoto
                  ? 'http://zxc.ruanjian211.top/' +
                    submitForm.industryQualification.certificatesPhoto
                  : ''
              "
              @photo-path="certificatesPhotoTwo"
            ></my-photo>
          </el-form-item>

          <el-form-item label="许可证编号" prop="licenseNumber">
            <el-input
              v-model="submitForm.industryQualification.licenseNumber"
              placeholder="请与资质照片上的保持一致"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="单位名称" prop="companyName">
            <el-input
              v-model="submitForm.industryQualification.companyName"
              placeholder="请输入单位名称"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="法定代表人" prop="legalPerson">
            <el-input
              v-model="submitForm.industryQualification.legalPerson"
              placeholder="请输入法定代表人名称"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="经营场所/住所" prop="businessAddress">
            <el-input
              v-model="submitForm.industryQualification.businessAddress"
              placeholder="请输入经营场所/住所名称"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="主体业态" prop="mainBusinessFormat">
            <el-input
              v-model="submitForm.industryQualification.mainBusinessFormat"
              placeholder="请输入主体业态"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="营业项目" prop="businessItem">
            <el-input
              v-model="submitForm.industryQualification.businessItem"
              placeholder="请输入营业项目"
              clearable
              style="width: 500px"
            />
          </el-form-item>
          <el-form-item label="有效期" prop="expirationDate">
            <el-date-picker
              v-model="submitForm.industryQualification.expirationDate"
              type="date"
              placeholder="请选择日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <div class="bottom">
    <div class="back" @click="back">
      <span>返回上一步</span>
    </div>
    <div class="next" @click="submitForm1">
      <span>下一步</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  getCurrentInstance,
} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { queryReq } from '@/utils/http/code'
import myPhoto from '@/views/register/components/public/myphoto.vue'
import { QualificationType } from '@/api/register/types/register'
import useSellerRegisterStore from '@/store/modules/register'
import {
  getQualificationInfo,
  submitQualification,
  getSubjectQualification,
  DictionariesType,
  getIndustryQualification,
} from '@/api/register/register'
const router = useRouter()

const { storeId } = toRefs(useSellerRegisterStore())

// 回到上一步
const back = () => {
  useSellerRegisterStore().nextPage('/cvmagic/register/qualification', false)
  router.back()
}
// 当前页面被销毁前卸载当前页面的路由
const swich = ref(false)

onBeforeUnmount(() => {
  if (!swich.value) {
    useSellerRegisterStore().nextPage('/cvmagic/register/qualification', false)
    console.log('qualification页面销毁')
  }
})

// 下一步
interface fromType {
  [key: string]: FormInstance | undefined
}
// 获取表单dom元素
const forms = reactive<fromType>({
  ruleFormRef: undefined,
  ruleFormRefTwo: undefined,
})
const { ruleFormRef, ruleFormRefTwo } = toRefs(forms)
// 提交表单时做的
const submitForm1 = () => {
  swich.value = true
  test((count: number) => {
    if (count != Object.keys(forms).length) {
      return
    }
    submit(submitForm.value)
  })
}

const test = (fun: Function) => {
  let count = 0
  for (const key in forms) {
    if (!forms[key]) return
    forms[key]?.validate((valid) => {
      if (valid) {
        count += 1
      } else {
        // 获取到错误的class类
        const list = document.getElementsByClassName('is-error')
        // 让其延迟执行.防止出现还没数据就执行
        setTimeout(() => {
          // 移动样式
          list[0].scrollIntoView({
            behavior: 'smooth', // 平滑过渡
            block: 'start', // 上边框与视窗顶部平齐
          })
          getchildNodes(list[0])
        }, 500)
        console.log('error submit!')
        return false
      }
      fun(count)
    })
  }
}
// 获取输入框焦点(使用到了递归)
const getchildNodes = (node: any) => {
  node.childNodes.forEach((v: any): void => {
    if (v?.className == 'el-input__inner' && v.className !== undefined) {
      v?.focus()
    }
    if (v.childNodes.length != 0) {
      getchildNodes(v)
    }
  })
}

const submit = async (item: QualificationType) => {
  const res = await submitQualification(item)
  queryReq(res, (data) => {
    useSellerRegisterStore().nextPage('/cvmagic/register/shop', true)
    router.push('/cvmagic/register/shop')
  })
}

// 证件类型
const subjectQualificationList = ref<DictionariesType[]>([] as any)
const IndustryQualificationList = ref<DictionariesType[]>([] as any)

//资质照片地址
const certificatesPhoto = (item: string) => {
  submitForm.value.subjectQualification.certificatesPhoto = item
}
// 主体照片地址
const certificatesPhotoTwo = (item: string) => {
  submitForm.value.industryQualification.certificatesPhoto = item
}

/**
 * 提交的表单
 */
const submitForm = ref<QualificationType>({
  industryQualification: {
    certificatesType: 1,
    certificatesPhoto: '',
    licenseNumber: '',
    companyName: '',
    legalPerson: '',
    businessAddress: '',
    mainBusinessFormat: '',
    businessItem: '',
    expirationDate: '',
    storeId: storeId.value as any,
    applyId: '',
  },
  subjectQualification: {
    certificatesType: 1,
    certificatesPhoto: '',
    registerNumber: '',
    companyName: '',
    legalPerson: '',
    businessAddress: '',
    expirationDate: '',
    storeId: storeId.value as any,
    applyId: '',
  },
})

/**
 * 验证规则
 */
const rules = reactive<FormRules>({
  certificatesType: [
    {
      required: true,
      message: '请选择证件类型',
      trigger: 'change',
    },
  ],
  certificatesPhoto: [
    {
      required: true,
      message: '请上传资质照片',
      trigger: 'blur',
    },
  ],
  registerNumber: [
    {
      required: true,
      message: '请输入注册号',
      trigger: 'change',
    },
    {
      max: 14,
      message: '请输入正确的注册号',
    },
  ],
  companyName: [
    {
      required: true,
      message: '请输入单位名称',
      trigger: 'blur',
    },
  ],
  legalPerson: [
    {
      required: true,
      message: '请输入法定代表人',
      trigger: 'blur',
    },
  ],
  businessAddress: [
    {
      required: true,
      message: '请输入经营场所',
      trigger: 'blur',
    },
  ],
  expirationDate: [
    {
      required: true,
      message: '请输入有效期',
      trigger: 'change',
    },
  ],
  licenseNumber: [
    {
      required: true,
      message: '请输入许可证编号',
      trigger: 'blur',
    },
  ],
  mainBusinessFormat: [
    {
      required: true,
      message: '请输入主体业态',
      trigger: 'blur',
    },
  ],
  businessItem: [
    {
      required: true,
      message: '请输入营业项目',
      trigger: 'blur',
    },
  ],
})

const initQualificationInfo = async () => {
  const res = await getQualificationInfo(useSellerRegisterStore().storeId)
  queryReq(res, (data) => {
    submitForm.value = data
  })
}
const initsubjectQualificationList = async () => {
  const res = await getSubjectQualification()
  subjectQualificationList.value = res.data
}
const initIndustryQualificationList = async () => {
  const res = await getIndustryQualification()
  IndustryQualificationList.value = res.data
}
initQualificationInfo()
initsubjectQualificationList()
initIndustryQualificationList()
</script>
<style lang="scss" scoped>
.content {
  margin-top: 30px;
  width: 100%;
  box-sizing: border-box;
  .public2 {
    display: flex;
    margin-top: 20px;
  }
  .content-left {
    width: 150px;
    font-size: 16px;
  }
  .content-right {
    .right-hint {
      padding: 2px 5px;
      background-color: #fdf6ea;
      font-size: 12px;
      color: #e6a23c;
      margin-bottom: 4px;
    }
    .map {
      .confirm {
        width: 50px;
        height: 20px;
        padding: 2px 0;
        background-color: #f56c6c;
        text-align: center;
        border-radius: 6px;
        line-height: 20px;
        cursor: pointer;
      }
    }
    .public {
      margin-top: 40px;
    }
  }
}
:deep(.anchorBL) {
  display: none !important;
}
.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 12px 44px;
  background: #fff;
  box-shadow: 0 -2px 15px 0 rgba(0, 0, 0, 0.05);
  .back {
    width: 76px;
    height: 34px;
    background-color: #fff;
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    margin-right: 10px;
    text-align: center;
    line-height: 34px;
    color: black;
    font-size: 12px;
    cursor: pointer;
  }
  .next {
    width: 76px;
    height: 34px;
    background-color: #1989fa;
    border-radius: 6px;
    text-align: center;
    line-height: 34px;
    color: #fff;
    font-size: 12px;
    cursor: pointer;
  }
}
</style>
